<template>
  <div class="home-layout">
    <!-- 中间内容区 -->
    <main class="home-main">
      <div class="main-content">
        <div class="content-grid">
          <!-- 最新文章列 -->
          <div class="grid-column">
            <a-card class="section-card" :bordered="false">
              <template #title>
                <span class="section-title">
                  <crown-outlined />
                  推荐文档
                </span>
              </template>
              <div class="doc-list">
                <a-spin :spinning="loading.latest">
                  <a-card 
                    v-for="doc in latestDocuments" 
                    :key="doc.id"
                    class="doc-item"
                    :bordered="false"
                    hoverable
                    @click="handleDocumentClick(doc)"
                  >
                    <div class="doc-info">
                      <h3>{{ doc.title }}</h3>
                      <p>{{ doc.description || '暂无描述' }}</p>
                      <div class="doc-meta">
                        <span><calendar-outlined /> {{ formatDate(doc.created_at) }}</span>
                        <span><eye-outlined /> {{ doc.views }}</span>
                      </div>
                    </div>
                  </a-card>
                </a-spin>
              </div>
            </a-card>
          </div>

          <!-- 推荐文档列 -->
          <div class="grid-column">
            <a-card class="section-card" :bordered="false">
              <template #title>
                <span class="section-title">
                  <crown-outlined />
                  推荐文档
                </span>
              </template>
              <div class="doc-list">
                <a-spin :spinning="loading.recommended">
                  <a-card 
                    v-for="doc in recommendedDocuments" 
                    :key="doc.id"
                    class="doc-item"
                    :bordered="false"
                    hoverable
                    @click="handleDocumentClick(doc)"
                  >
                    <div class="doc-info">
                      <h3>{{ doc.title }}</h3>
                      <p>{{ doc.description || '暂无描述' }}</p>
                      <div class="doc-meta">
                        <span><calendar-outlined /> {{ formatDate(doc.created_at) }}</span>
                        <span><eye-outlined /> {{ doc.views }}</span>
                      </div>
                    </div>
                  </a-card>
                </a-spin>
              </div>
            </a-card>
          </div>

          <!-- 右侧：分类导航和热门文章 -->
          <div class="grid-column">
            <!-- 标签云 -->
            <a-card class="section-card" :bordered="false">
              <template #title>
                <span class="section-title">
                  <thunderbolt-outlined />
                  标签云
                </span>
              </template>
              <a-spin :spinning="loading.tags">
                <div class="tag-cloud" v-if="tags.length">
                  <a-tag
                    v-for="tag in tags"
                    :key="tag.id"
                    :color="getTagColor(tag.weight)"
                    class="tag-item"
                    @click="handleTagClick(tag)"
                  >
                    {{ tag.name }}
                    <span class="tag-count" v-if="tag.document_count">
                      ({{ tag.document_count }})
                    </span>
                  </a-tag>
                </div>
                <a-empty v-else description="暂无标签" />
              </a-spin>
            </a-card>

            <!-- 热门文章 -->
            <a-card class="section-card" :bordered="false">
              <template #title>
                <span class="section-title">
                  <fire-outlined />
                  热门文章
                </span>
              </template>
              <a-list :data-source="popularDocuments" :loading="loading.popular" size="small">
                <template #renderItem="{ item }">
                  <a-list-item>
                    <div class="hot-article-item" @click="handleDocumentClick(item)">
                      <div class="hot-article-rank">{{ item.rank || '#' }}</div>
                      <div class="hot-article-content">
                        <div class="hot-article-title">{{ item.title }}</div>
                        <div class="hot-article-meta">
                          <span class="hot-article-views">
                            <fire-outlined /> {{ item.views }}
                          </span>
                          <span class="hot-article-date">
                            <calendar-outlined /> {{ formatDate(item.created_at) }}
                          </span>
                        </div>
                      </div>
                    </div>
                  </a-list-item>
                </template>
              </a-list>
            </a-card>
          </div>
        </div>
      </div>
    </main>

    <!-- 底部页脚 -->
    <footer class="home-footer">
      <div class="footer-content">
        <p>© 2024 运维知识库. All rights reserved.</p>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { 
  EyeOutlined, 
  FireOutlined,
  CrownOutlined,
  ClockCircleOutlined,
  ThunderboltOutlined,
  CalendarOutlined,
  FolderOutlined
} from '@ant-design/icons-vue'
import { documentApi, categoryApi, tagApi } from '@/utils/api'

const router = useRouter()

// 数据状态
const latestDocuments = ref([])
const recommendedDocuments = ref([])
const popularDocuments = ref([])
const tags = ref([])

// 加载状态
const loading = ref({
  latest: false,
  recommended: false,
  popular: false,
  tags: false,
})

// 获取最新文档
const fetchLatestDocuments = async () => {
  loading.value.latest = true
  try {
    const { code, data } = await documentApi.getLatest()
    if (code === 0) {
      latestDocuments.value = data
    }
  } catch (error) {
    message.error('获取最新文档失败')
    console.error(error)
  } finally {
    loading.value.latest = false
  }
}

// 获取推荐文档
const fetchRecommendedDocuments = async () => {
  loading.value.recommended = true
  try {
    const { code, data } = await documentApi.getRecommended()
    if (code === 0) {
      recommendedDocuments.value = data
    }
  } catch (error) {
    message.error('获取推荐文档失败')
    console.error(error)
  } finally {
    loading.value.recommended = false
  }
}

// 获取热门文档
const fetchPopularDocuments = async () => {
  loading.value.popular = true
  try {
    const { code, data } = await documentApi.getPopular()
    if (code === 0) {
      popularDocuments.value = data
    }
  } catch (error) {
    message.error('获取热门文档失败')
    console.error(error)
  } finally {
    loading.value.popular = false
  }
}

// 获取标签云数据
const fetchTags = async () => {
  loading.value.tags = true
  try {
    const res = await tagApi.getList()
    console.log('[Home] Tag data:', res)
    if (res?.code === 0) {
      // 过滤掉无效的标签并计算权重
      tags.value = res.data
        .filter(tag => tag.name && tag.name !== '###' && tag.slug && tag.slug.trim() !== '')
        .map(tag => ({
          ...tag,
          weight: calculateWeight(tag.document_count || 0)
        }))
      console.log('[Home] Processed tags:', tags.value)
    }
  } catch (error) {
    message.error('获取标签云失败')
    console.error(error)
  } finally {
    loading.value.tags = false
  }
}

// 根据文档数量计算标签权重（1-5）
const calculateWeight = (count) => {
  if (!count) return 1
  if (count < 5) return 1
  if (count < 10) return 2
  if (count < 20) return 3
  if (count < 50) return 4
  return 5
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 处理文档点击
const handleDocumentClick = (doc) => {
  if (doc.category) {
    router.push({
      path: '/document',
      query: { 
        category: doc.category.slug,
        doc: doc.slug
      }
    })
  } else {
    message.error('文档分类信息不存在')
  }
}

// 处理标签点击
const handleTagClick = (tag) => {
  router.push(`/tags/${tag.slug}`)
}

// 获取标签颜色
const getTagColor = () => {
  // 预定义一组柔和的颜色
  const colors = [
    '#40a9ff',  // 蓝色
    '#73d13d',  // 绿色
    '#ffa940',  // 橙色
    '#9254de',  // 紫色
    '#36cfc9',  // 青色
  ]
  // 随机选择一个颜色
  return colors[Math.floor(Math.random() * colors.length)]
}

// 组件挂载时获取数据
onMounted(() => {
  fetchLatestDocuments()
  fetchRecommendedDocuments()
  fetchPopularDocuments()
  fetchTags()
})
</script>

<style scoped>
.home-layout {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.home-main {
  padding: 16px;
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
}

.content-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.grid-column {
  min-width: 0;
}

.section-card {
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.section-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f1f1f;
  display: flex;
  align-items: center;
  gap: 8px;
}

.article-item {
  cursor: pointer;
  padding: 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
  background-color: #fff;
  border: 1px solid #f0f0f0;
  margin-bottom: 8px;
}

.article-item:hover {
  background-color: #f0f7ff;
  border-color: #91caff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.article-item h3 {
  margin: 0 0 8px;
  font-size: 16px;
  line-height: 1.4;
  color: #1f1f1f;
  font-weight: 500;
}

.article-item p {
  margin: 0 0 8px;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #999;
  align-items: center;
}

.article-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.article-meta .anticon {
  font-size: 14px;
}

.tag-cloud {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px;
}

.tag-item {
  cursor: pointer;
  transition: all 0.3s ease;
  margin: 0;
  font-size: 13px;
  border-radius: 4px;
}

.tag-item:hover {
  transform: translateY(-1px);
}

.tag-count {
  margin-left: 2px;
  opacity: 0.8;
}

.hot-article-item {
  cursor: pointer;
  padding: 12px;
  border-radius: 8px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 12px;
  position: relative;
  width: 100%;
  background-color: #fff;
  border: 1px solid #f0f0f0;
  margin-bottom: 8px;
}

.hot-article-item:hover {
  background-color: #f0f7ff;
  border-color: #91caff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.hot-article-rank {
  font-size: 16px;
  font-weight: bold;
  color: #ff4d4f;
  min-width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff2f0;
  border-radius: 6px;
  padding: 0 6px;
}

.hot-article-content {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.hot-article-title {
  font-size: 14px;
  font-weight: 500;
  color: #1f1f1f;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.hot-article-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 12px;
  color: #999;
}

.hot-article-views {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #ff4d4f;
}

.hot-article-date {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 修改列表样式 */
.ant-list-item {
  padding: 0 !important;
  border-bottom: none !important;
}

.ant-list {
  padding: 8px;
}

.doc-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.doc-item {
  cursor: pointer;
  padding: 16px;
  margin: 0 0 8px;
  border-radius: 8px;
  background-color: #fff;
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.doc-item:hover {
  background-color: #f0f7ff;
  border-color: #91caff;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.doc-info {
  width: 100%;
}

.doc-info h3 {
  margin: 0 0 8px;
  font-size: 16px;
  line-height: 1.4;
  color: #1f1f1f;
  font-weight: 500;
}

.doc-info p {
  margin: 0 0 8px;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.doc-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #999;
  align-items: center;
}

.doc-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.doc-meta .anticon {
  font-size: 14px;
}

@media (max-width: 1200px) {
  .content-grid {
    grid-template-columns: 1fr 1fr;
  }
}

@media (max-width: 768px) {
  .content-grid {
    grid-template-columns: 1fr;
  }
  
  .home-main {
    padding: 12px;
  }
}
</style> 